package cn.fl.project.controller;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysOrgApiService;
import cmm.user.facade.system.condition.SysUsrFunAuthRQueryCondition;
import cmm.user.facade.system.dto.SysOrgDTO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.service.ICapFundSummaryService;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.condition.PrjTransLogQueryCondition;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.project.service.IPrjTransLogService;
import cn.fl.project.service.IPrjTransSettingService;
import cn.fl.project.vo.PrjBscInfoVO;
import cn.fl.project.vo.PrjTransLogVO;
import cn.fl.project.vo.PrjTransSettingVO;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysOrgService;
import cn.fl.system.vo.SysOrgVO;
import com.alibaba.fastjson.JSONObject;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: 项目转办记录表 控制层
 */
@Controller
@RequestMapping("/project/prjTransLog")
public class PrjTransLogController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(PrjTransLogController.class);
	
	/**
	 * PrjTransLog 服务层BEAN
	 */
	@Autowired
	private IPrjTransLogService prjTransLogService;

	/**
	 * 数据字典 服务层BEAN
	 */
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;

	/**
	 * PrjBscInfo 服务层BEAN
	 */
	@Autowired
	private IPrjBscInfoService prjBscInfoService;//项目基础信息表

	@Autowired
	private ISysOrgApiService sysOrgApiService;// 组织机构

	@Autowired
	private ICapFundSummaryService capFundSummaryService ;

	@Autowired
	private IPrjTransSettingService prjTransSettingService;

	@Autowired
	private ISysOrgService sysOrgService;


	/**
	 * 客户 服务层BEAN
	 */
	@Autowired
	private ICstBscInfoService cstBscInfoService;//客户基础信息表

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toListPage", "加载PrjTransLog列表页面.", CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("project/prjTransLog/prjTransLogList");
		// 事业部
		List<KeyValueVO> orgList = this.cstBscInfoService.searchBusinessOrgList();
		String currentOrgCd = CurrentThreadContext.getCurrentOrgCd();
		if(currentOrgCd.length()>8){
			if(CollectionUtils.isNotEmpty(orgList)){
				for(KeyValueVO kv:orgList){
					if(kv.getKey().equals(currentOrgCd.substring(0, 8))){
						mav.addObject("currOrg", CurrentThreadContext.getCurrentOrgCd());
						break;
					}
				}
			}
		}
		// 所属区域
		List<KeyValueVO> regionList = this.prjBscInfoService.getRegionList();
		mav.addObject("orgListList", orgList);
		mav.addObject("regionList", regionList);
		mav.addObject("currentBuOrgCd", CurrentThreadContext.getCurrentBuOrgCd());
		//this.prepare(request, mav);
		return mav;
	}
	
	/**
	 * 到新增页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toAddPage", "加载PrjTransLog Add页面.", CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("project/prjTransLog/prjTransLogModify");
		//this.prepare(request,mav);
		return mav;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toModifyPage", "加载PrjTransLog Modify页面.", CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("project/prjTransLog/prjTransLogModify");
		//this.prepare(request,mav);
		
		String id=request.getParameter("id");
		PrjTransLogVO prjTransLogVO = this.prjTransLogService.selectById(Long.valueOf(id));
        mav.addObject("prjTransLogVO", prjTransLogVO);
		return mav;
	}
	
	//加载数据字典数据、传值等 ？
    public void prepare(HttpServletRequest request,ModelAndView mav){
    	
    }

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public Object initPrjTransLogList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String prjNm = request.getParameter("prjNm");
		String lsCntNo = request.getParameter("lsCntNo");
		String buOrgCd = request.getParameter("buOrgCd");// 事业部
		String crtUsrNm = request.getParameter("crtUsrNm");// 创建人
		String stDt = request.getParameter("stDt");
		String endDt = request.getParameter("endDt");
		String cstMgrRgnCd = request.getParameter("cstMgrRgnCd");// 所属区域
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		PrjTransLogQueryCondition qc = new PrjTransLogQueryCondition();
		//TODO 设置查询条件？
		if (StringUtils.isNotEmpty(cstMgrRgnCd)) {
			qc.setNewCstMgrRgnCd(cstMgrRgnCd);//所属区域
		}
		if (StringUtils.isNotBlank(prjNm)) {
			qc.setPrjNm(prjNm);
		}
		if (StringUtils.isNotBlank(lsCntNo)) {
			qc.setLsCntNo(lsCntNo);
		}
		if (StringUtils.isNotBlank(buOrgCd)) {
			qc.setBuOrgCd(buOrgCd);
		}
		if (StringUtils.isNotBlank(crtUsrNm)) {
			qc.setCrtUsrNm(crtUsrNm);
		}
		if(StringUtils.isNotBlank(stDt)){
			stDt = stDt + " 00:00:00";
			qc.setStDt(DateUtils.formatStringToDate(stDt, DateUtils.YYYY_MM_DDHHMMSS));
		}
		if(StringUtils.isNotBlank(endDt)){
			endDt = endDt + " 23:59:59";
			qc.setEndDt(DateUtils.formatStringToDate(endDt, DateUtils.YYYY_MM_DDHHMMSS));
		}
		qc.setSysCd(CurrentThreadContext.getFlServiceSysCd());
		qc.setUsrId(CurrentThreadContext.getCurrentUserId());
		page.setCondition(qc);

		BaseLogUtils.info(logger, "initPrjTransLogList", "初始化PrjTransLog列表页面数据.DATA:"+JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		Pager pager = this.prjTransLogService.searchListPage(page);
		List<PrjTransLogVO> list = (List<PrjTransLogVO>) pager.getResultList();
		List<SysOrgDTO> orglist = this.sysOrgApiService.searchSysOrgListBy(CurrentThreadContext.getCurrentSysCd());
		Map<String, SysOrgDTO> buOrgCdMap = new HashMap<>();
		if (CollectionUtils.isNotEmpty(orglist)) {
			for (SysOrgDTO sysOrgDTO : orglist) {
				buOrgCdMap.put(sysOrgDTO.getOrgCd(), sysOrgDTO);
			}
		}
		SysOrgDTO sysOrgDTO = null;
		String orgCd = null;
		Long prjId = null;
		PrjBscInfoVO prjBscInfoVO = null;
		if(list != null && list.size() != 0){
			for (PrjTransLogVO prj : list){
				prjId = prj.getPrjId();
				prjBscInfoVO = this.prjBscInfoService.selectById(prjId);
				prj.setPrjNm(prjBscInfoVO.getPrjNm());
				prj.setLsCntNo(prjBscInfoVO.getLsCntNo());
				prj.setCstNm(prjBscInfoVO.getCstNm());
				prj.setCrtUsrNm(prjBscInfoVO.getCrtUsrNm());
				prj.setBuOrgCdNm(prjBscInfoVO.getBuOrgCdNm());
				prj.setPrjTypCdNm(prjBscInfoVO.getPrjTypCdNm());
				prj.setBizTypCdNm(prjBscInfoVO.getBizTypCdNm());
				if (buOrgCdMap.containsKey(prj.getNewCstMgrOrgCd())) {
					sysOrgDTO = buOrgCdMap.get(prj.getNewCstMgrOrgCd());
					prj.setCstMgrOrgCdNm(sysOrgDTO.getOrgNm());
					orgCd = sysOrgDTO.getOrgCd();
					while(orgCd.length()>8){
						if("4".equals(sysOrgDTO.getOrgTypCd())){//分公司
							prj.setCyOrgCdNm(sysOrgDTO.getOrgNm());
						}else if("3".equals(sysOrgDTO.getOrgTypCd())){
							prj.setPrOrgCdNm(sysOrgDTO.getOrgNm());
							break;
						}
						orgCd = orgCd.substring(0,orgCd.length()-4);
						if(buOrgCdMap.containsKey(orgCd)){
							sysOrgDTO = buOrgCdMap.get(orgCd);
						}else{
							break;
						}
					}
				}

			}
		}
		ListPageVO<PrjTransLogVO> listPage = new ListPageVO<PrjTransLogVO>(list, pager.getTotalCount());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removePrjTransLogByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(ids)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "removePrjTransLogByIds", "删除PrjTransLog数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        List<Long> idsList = new ArrayList<Long>();
        JSONArray idsArray = JSONArray.fromObject(ids);
        for (Object object : idsArray) {
            idsList.add(Long.valueOf(object.toString()));
        }
		
		try {
			boolean success = this.prjTransLogService.removeByIds(idsList);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
				BaseLogUtils.info(logger, "removePrjTransLogByIds", "删除PrjTransLog数据失败,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "removePrjTransLogByIds", "删除PrjTransLog数据成功,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "removePrjTransLogByIds", "删除PrjTransLog数据失败,ID:"+idsList.toString()+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removePrjTransLogByIds", "删除PrjTransLog数据失败,系统错误.ID:"+idsList.toString()+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getPrjTransLogById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "getPrjTransLogById", "获取PrjTransLog数据,主键参数为空.", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			PrjTransLogVO vo = this.prjTransLogService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getPrjTransLogById", "获取PrjTransLog数据不存在,ID:"+id, CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getPrjTransLogById", "获取PrjTransLog数据成功,ID:"+id, CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "getPrjTransLogById", "获取PrjTransLog数据失败,ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getPrjTransLogById", "获取PrjTransLog数据失败,系统错误.ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object addPrjTransLog(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		PrjTransLogVO entity = null;//获取参数
		try {
			entity = this.getRequestParamForPrjTransLog(request);//获取参数
			Long id = this.prjTransLogService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "addPrjTransLog", "新增PrjTransLog数据成功,ID:"+id+".DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.info(logger, "addPrjTransLog", "新增PrjTransLog数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.error(logger, "addPrjTransLog", "新增PrjTransLog数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modifyPrjTransLog(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		PrjTransLogVO entity = null;
		try {
			entity = this.getRequestParamForPrjTransLog(request);
			if(entity.getId()==null){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
				BaseLogUtils.info(logger, "modifyPrjTransLog", "修改PrjTransLog信息,主键参数为空！.", CurrentThreadContext.getCurrentUserName());
				return result;
			}

			boolean success = this.prjTransLogService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
				BaseLogUtils.info(logger, "modifyPrjTransLog", "修改PrjTransLog数据失败.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
				return result;
			}
			BaseLogUtils.info(logger, "modifyPrjTransLog", "修改PrjTransLog数据成功.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.info(logger, "modifyPrjTransLog", "修改PrjTransLog数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.error(logger, "modifyPrjTransLog", "修改PrjTransLog数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 获取请求参数
	 * @param request 请求
	 * @return 
	 */
	private PrjTransLogVO getRequestParamForPrjTransLog(HttpServletRequest request) throws BaseException {
		//获取参数
		String id = request.getParameter("id");//主键
		String prjId = request.getParameter("prjId");//项目ID
		String cstMgrId = request.getParameter("cstMgrId");//转办人ID(原客户经理ID)
		String cstMgrNm = request.getParameter("cstMgrNm");//转办人名称(原客户经理名称)
		String cstMgrOrgCd = request.getParameter("cstMgrOrgCd");//转办人组织架构(原客户经理组织架构代码)
		String newCstMgrId = request.getParameter("newCstMgrId");//被转办人ID(新客户经理ID)
		String newCstMgrNm = request.getParameter("newCstMgrNm");//被转办人名称(新客户经理名称)
		String newCstMgrOrgCd = request.getParameter("newCstMgrOrgCd");//被转办人组织架构(新客户经理组织架构代码)
		String transRem = request.getParameter("transRem");//转办备注
		String cstMgrRgnCd = request.getParameter("cstMgrRgnCd");// 转办人区域ID
		String newCstMgrRgnCd = request.getParameter("newcstMgrRgnCd");// 被转办人区域ID

		//验证参数并赋值
		PrjTransLogVO entity = new PrjTransLogVO();
 		entity.setPrjId(Long.valueOf(prjId));//项目ID
 		entity.setCstMgrId(Long.valueOf(cstMgrId));//转办人ID(原客户经理ID)
 		entity.setCstMgrNm(cstMgrNm);//转办人名称(原客户经理名称)
 		entity.setCstMgrOrgCd(cstMgrOrgCd);//转办人组织架构(原客户经理组织架构代码)
 		entity.setNewCstMgrId(Long.valueOf(newCstMgrId));//被转办人ID(新客户经理ID)
 		entity.setNewCstMgrNm(newCstMgrNm);//被转办人名称(新客户经理名称)
 		entity.setNewCstMgrOrgCd(newCstMgrOrgCd);//被转办人组织架构(新客户经理组织架构代码)
 		entity.setTransRem(transRem);//转办备注
		entity.setCstMgrRgnCd(cstMgrRgnCd);
		entity.setNewCstMgrRgnCd(newCstMgrRgnCd);
	
//		if (StringUtils.isBlank(name)) {
//            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "名称不能为空.");
//      }
//      if (StringUtils.isNotBlank(num)) {
//          if (!StringUtils.isUnsignedNumeric(num)) {
//                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请填写正确的数字.");
//          }
//      }

		Date tm=new Date();
		if (StringUtils.isNotBlank(id)) {
			entity.setId(Long.valueOf(id));
			entity.setMdfTm(tm);
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
		}else{
			entity.setCrtTm(tm);
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			//entity.setCrtUsrOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前用户组织机构代码
            //entity.setOrgCd(CurrentThreadContext.getCurrentBuOrgCd());//事业部组织机构代码
		}
		
		return entity;
	}

}

